-- LuaTools需要PROJECT和VERSION这两个信息
PROJECT = "gnsstest"
VERSION = "1.0.1"

-- sys库是标配
local sys = require("sys")

hw = require("hwIot")
require("sysplus")
require("gnss")

-- Air780E的AT固件默认会为开机键防抖, 导致部分用户刷机很麻烦
if rtos.bsp() == "EC618" and pm and pm.PWK_MODE then
    pm.power(pm.PWK_MODE, false)
end

-- 退出飞行模式
mobile.flymode(0, false)

local stm_res = {}
local PRODUCT_ID = "6645bd39d5a39615670a4513"

-- libgnss库初始化
libgnss.clear() -- 清空数据,兼初始化

-- LED和ADC初始化
LED_G = 27
LED_R = 26
gpio.setup(LED_G, 0) -- GNSS定位成功灯
gpio.setup(LED_R, 0) -- 低电压警告灯
adc.open(adc.CH_VBAT)
adc.open(adc.CH_CPU)

uart.setup(1, 9600)

-- 分割字符串
function Split(szFullString, szSeparator)
    local nFindStartIndex = 1
    local nSplitIndex = 1
    local nSplitArray = {}
    while true do
        local nFindLastIndex = string.find(szFullString, szSeparator,
                nFindStartIndex)
        if not nFindLastIndex then
            nSplitArray[nSplitIndex] = string.sub(szFullString, nFindStartIndex,
                    string.len(szFullString))
            break
        end
        nSplitArray[nSplitIndex] = string.sub(szFullString, nFindStartIndex,
                nFindLastIndex - 1)
        nFindStartIndex = nFindLastIndex + string.len(szSeparator)
        nSplitIndex = nSplitIndex + 1
    end
    return nSplitArray
end

uart.on(1, "receive", function(id, len)
    local s = ""
    repeat
        s = uart.read(id, 128)
        if #s > 0 then
            log.info("uart", "receive", s)
            local res = Split(s, ",")
            for i, v in ipairs(res) do
                log.info(i, v)
            end
            if #res == 3 then
                stm_res = res
            end
        end
    until s == ""
end)

local function dataPost(data_list)
    local topic = "$oc/devices/" .. PRODUCT_ID .. "_GNS_" .. mobile.imei() ..
            "/sys/properties/report"
    local re = {
        services = {
            {
                service_id = "sensor",
                properties = {
                    lon = data_list[1],
                    lat = data_list[2],
                    speed = data_list[3] * 1.852,
                    sim = mobile.iccid(),
                    --sim = mobile.iccid()
                }
            }

        }
    }
    if #stm_res > 0 then
        re["services"][1]["properties"]["temp"] = stm_res[1]
        re["services"][1]["properties"]["hum"] = stm_res[2]
    end

    re = json.encode(re)
    log.info("mqtt", topic, re)
    sys.publish("mqtt_pub", topic, re)
end

-- 主循环
sys.taskInit(function()
    gpio.set(LED_R, 1)

    hw.hwGetToken()
    hw.connectHw()
    -- 华为iot连接失败，闪红灯
    while 1 do
        if hw.hwIsReady() == false then
            gpio.set(LED_R, 1)
            sys.wait(50)
            gpio.set(LED_R, 0)
            sys.wait(50)
        else
            break
        end
    end

    while 1 do
        local vbat = adc.get(adc.CH_VBAT)
        log.info("vbat", vbat)
        local net_state = mobile.status()
        if net_state == 1 then
            gpio.set(LED_G, 1)
            gpio.set(LED_R, 0)
        else
            gpio.set(LED_G, 0)
            gpio.set(LED_R, 1)
        end

        if vbat < 3200 then
            gpio.set(LED_R, 1)
            sys.wait(500)

            sys.wait(200)
        end
        sys.wait(1000)
        local res = libgnss.getRmc(2)
        log.info("RMC", json.encode(res or {}, "7f"))
        log.info("RMC", res["valid"])
        if res["valid"] == true then
            dataPost({ res["lng"], res["lat"], res["speed"] })
            gpio.set(LED_R, 0)
            gpio.set(LED_G, 1)
            sys.wait(100)
            gpio.set(LED_G, 0)
            sys.wait(100)
            gpio.set(LED_G, 1)
            sys.wait(100)
            gpio.set(LED_G, 0)
            sys.wait(100)
            gpio.set(LED_G, 1)
            sys.wait(100)
            gpio.set(LED_G, 0)
            sys.wait(100)

            sys.wait(2000)

            mobile.flymode(0, true)
            pm.power(pm.WORK_MODE, 3) -- 进入极致功耗模式
            log.info(rtos.meminfo("sys"))
            sys.wait(15000) -- demo演示唤醒时间是一分钟，如果15s后模块重启，则说明进入极致功耗模式失败，
            log.info("进入极致功耗模式失败，尝试重启")
            rtos.reboot()

        else
            gpio.set(LED_G, 0)
            gpio.set(LED_R, 1)
            sys.wait(100)
            gpio.set(LED_R, 0)
            sys.wait(100)
            gpio.set(LED_R, 1)
            sys.wait(100)
            gpio.set(LED_R, 0)
            sys.wait(100)
            gpio.set(LED_R, 1)
            sys.wait(100)
            gpio.set(LED_R, 0)
            sys.wait(100)
        end
        log.info("INT", libgnss.getIntLocation())
        log.info("sys", rtos.meminfo("sys"))
        log.info("lua", rtos.meminfo("lua"))

    end
end)

sys.run()
